package com.joven.product.api.business.client;

import com.joven.infra.common.model.PageResult;
import com.joven.infra.common.model.Response;
import com.joven.product.api.business.client.feign.ProductService;
import com.joven.product.api.business.client.model.*;
import com.joven.product.api.infrastructure.converter.ProductConverter;
import com.joven.product.service.client.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品客户端实现
 *
 * @author Joven
 * @date 2022-01-06 18:21:27
 */
@Slf4j
@Component
public class ProductClient {
    @Resource
    private ProductService remoteProductService;

    /**
     * 新建商品
     *
     * @param cmd
     * @return
     */
    public boolean create(ProductCreateCmd cmd) {
        ProductCreateDTO dto = ProductConverter.INSTANCE.convert(cmd);
        Response<Boolean> result = remoteProductService.create(dto);
        result.checkResult();
        return result.getData();
    }

    /**
     * 编辑商品
     *
     * @param cmd
     * @return
     */
    public boolean edit(ProductEditCmd cmd) {
        ProductEditDTO dto = ProductConverter.INSTANCE.convert(cmd);
        Response<Boolean> result = remoteProductService.edit(dto);
        result.checkResult();
        return result.getData();
    }

    /**
     * 分页查询
     *
     * @param pageQuery
     * @return
     */
    public PageResult<Product> getByPage(ProductPageQuery pageQuery) {
        ProductPageQueryDTO dto = ProductConverter.INSTANCE.convert(pageQuery);
        Response<PageResult<ProductDTO>> result = remoteProductService.getByPage(dto);
        result.checkResult();
        PageResult<ProductDTO> page = result.getData();
        PageResult<Product> pageResult = (PageResult) page;
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return pageResult;
        }
        List<Product> list = page.getRecords().stream()
                .map(ProductConverter.INSTANCE::convert).collect(Collectors.toList());
        pageResult.setRecords(list);
        return pageResult;
    }

    /**
     * 根据id查询详情
     *
     * @param id
     * @return
     */
    public ProductDetail getDetailById(Long id) {
        Response<ProductDetailDTO> result = remoteProductService.getDetailById(id);
        result.checkResult();
        return ProductConverter.INSTANCE.convert(result.getData());
    }
}
